define(["jquery", "easy-admin", "echarts", "echarts-theme", "miniAdmin", "miniTheme", "miniTab", "swiper"], function ($, ea, echarts, undefined, miniAdmin, miniTheme, miniTab) {

    function getToDay() {
        var now = new Date();
        var year = now.getFullYear();//获取当前年份
        var month = now.getMonth() + 1;//当前月份
        if (month < 10)
            month = "0" + month;
        else {
            month = month;
        }
        var day = now.getDate();//当前天份
        if (day < 10)
            day = "0" + day;
        else {
            day = day;
        }
        return year + "-" + month + "-" + day;
    }
    /**
     * 全局通知管理器
     */
    class GlobalNoticeManager {
        constructor() {
            this.noticeContainer = document.createElement('div');
            this.noticeContainer.className = 'global-notice-container';
            document.body.appendChild(this.noticeContainer);

            // 避免重复初始化（通过 localStorage 标记）
            if (!window.globalNotice) {
                this.checkNewNotices(); // 首次加载检查通知
                // window.globalNotice = getToDay(); // 标记已初始化
            }
            // 在 GlobalNoticeManager 构造函数中添加
            this.taskNum = 0;
            this.runTask();
        }

        runTask() {
            this.pollTimer = setInterval(() => {
                requestIdleCallback(() => {
                    this.checkNewNotices()
                    this.taskNum++;
                    if (this.taskNum > 10) {
                        clearInterval(this.pollTimer);
                        this.runTask();
                    }
                }, {timeout: 1000})
            }, 30000); // 30秒轮询
        }

        /**
         * 检查并显示新通知
         */
        checkNewNotices() {

            ea.request.fetch(
                'insurance.policy/getnotice',
                { renewal: 1 },
            ).then(res => {
                // console.log(res);
                if (res.code == 1) {
                    if (!window.globalNotice) {
                        this.showNotice(res.data);
                        window.globalNotice = res.date;
                    }
                }
            })
        }

        /**
         * 显示通知列表
         */
        showNotices(notices) {
            notices.forEach(notice => {
                const noticeEl = document.createElement('div');
                noticeEl.className = 'global-notice-item';
                noticeEl.innerHTML = `
                    <div class="global-notice-title">${notice.title}</div>
                    <div class="global-notice-content">${notice.content}</div>
                    <span class="global-notice-close" data-id="${notice.id}">×</span>
                `;
                this.noticeContainer.prepend(noticeEl); // 新通知放在最上面

                // 绑定关闭事件
                noticeEl.querySelector('.global-notice-close').addEventListener('click', () => {
                    this.closeNotice(noticeEl, notice.id);
                });

                // // 自动关闭（5秒后）
                // setTimeout(() => {
                //     noticeEl.style.opacity = '0';
                //     noticeEl.style.transform = 'translateX(100%)';
                //     setTimeout(() => noticeEl.remove(), 300);
                // }, 5000);
            });
        }
        /**
         * 显示通知列表
         */
        showNotice(notice) {
            const noticeEl = document.createElement('div');
            noticeEl.className = 'global-notice-item';
            noticeEl.innerHTML = `
                <div class="global-notice-title">${notice.notice_title}</div>
                <div class="global-notice-content">
                <a layuimini-href="Insurance.policy/renewals" href="javascript:;" data-url="insurance.policy/index">${notice.notice_content}</a>
                </div>
                <span class="global-notice-close" data-id="${notice.id}">×</span>
            `;
            this.noticeContainer.prepend(noticeEl); // 新通知放在最上面

            // 绑定关闭事件
            noticeEl.querySelector('.global-notice-close').addEventListener('click', () => {
                this.closeNotice(noticeEl, notice.id);
            });
        }

        /**
         * 关闭单个通知（前端隐藏 + 后端标记已读）
         */
        closeNotice(noticeEl, noticeId) {
            // 前端移除元素
            noticeEl.style.opacity = '0';
            noticeEl.style.transform = 'translateX(100%)';
            setTimeout(() => noticeEl.remove(), 300);

            ea.request.fetch(
                'insurance.policy/setnotice',
                {id: noticeId },
            ).then(res => {
                console.log(res);

            })
        }

        /**
         * 记录已显示的通知（避免刷新后重复弹）
         */
        markAsShown(notices) {
            const shownIds = localStorage.getItem('globalNoticeShown')
                ? JSON.parse(localStorage.getItem('globalNoticeShown'))
                : [];
            const newShownIds = [...new Set([...shownIds, ...notices.map(n => n.id)])];
            localStorage.setItem('globalNoticeShown', JSON.stringify(newShownIds));
        }
    }

    // 初始化全局通知管理器（页面加载完成后执行）
    $(function () {
        if (self === top) {
            var notice = new GlobalNoticeManager();
        }
    });
    return {
        index: function () {
            var options = {
                iniUrl: ea.url('ajax/initAdmin'),    // 初始化接口
                clearUrl: ea.url("ajax/clearCache"), // 缓存清理接口
                urlHashLocation: true,      // 是否打开hash定位
                bgColorDefault: false,      // 主题默认配置
                multiModule: true,          // 是否开启多模块
                menuChildOpen: false,       // 是否默认展开菜单
                loadingTime: 0,             // 初始化加载时间
                pageAnim: true,             // iframe窗口动画
                maxTabNum: 20,              // 最大的tab打开数量
            };
            miniAdmin.render(options);

            $('.login-out').on("click", function () {
                ea.request.get({
                    url: 'login/out',
                    prefix: true,
                }, function (res) {
                    ea.msg.success(res.msg, function () {
                        window.location = ea.url('login/index');
                    })
                });
            });
        },
        welcome: function () {
            miniTab.listen();

            new Swiper('.mySwiper', {
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
            })

            /**
             * 查看公告信息
             **/
            $('body').on('click', '.layuimini-notice', function () {
                var title = $(this).children('.layuimini-notice-title').text(),
                    noticeTime = $(this).children('.layuimini-notice-extra').text(),
                    content = $(this).children('.layuimini-notice-content').html();
                var html = '<div style="padding:15px 20px; text-align:justify; line-height: 22px;border-bottom:1px solid #e2e2e2;background-color: #2f4056;color: #ffffff">\n' +
                    '<div style="text-align: center;margin-bottom: 20px;font-weight: bold;border-bottom:1px solid #718fb5;padding-bottom: 5px"><h4 class="text-danger">' + title + '</h4></div>\n' +
                    '<div style="font-size: 12px">' + content + '</div>\n' +
                    '</div>\n';
                layer.open({
                    type: 1,
                    title: '系统公告' + '<span style="float: right;right: 1px;font-size: 12px;color: #b1b3b9;margin-top: 1px">' + noticeTime + '</span>',
                    area: '300px;',
                    shade: 0.8,
                    id: 'layuimini-notice',
                    btn: ['查看', '取消'],
                    btnAlign: 'c',
                    moveType: 1,
                    content: html,
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        // btn.find('.layui-layer-btn0').attr({
                        //     href: 'https://gitee.com/zhongshaofa/layuimini',
                        //     target: '_blank'
                        // });
                    }
                });
            });

            /**
             * 报表功能
             */
            $(function () {
                $('#layui-version').text('v' + layui.v);
                let echartsRecords = echarts.init(document.getElementById('echarts-records'), 'walden');
                let optionRecords = {
                    title: {
                        text: '每月每日出单统计'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: agents
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: allDays
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: d_data
                };
                echartsRecords.setOption(optionRecords);
                let echartsRecords1 = echarts.init(document.getElementById('echarts-records1'), 'walden');
                let optionRecords1 = {
                    title: {
                        text: '每年每月出单统计'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: agents
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: months
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: m_data
                };
                echartsRecords1.setOption(optionRecords1);
                window.addEventListener("resize", function () {
                    echartsRecords.resize();
                    echartsRecords1.resize();
                });
            })

            let util = layui.util;
            util.on({
                showComposerInfo: function () {
                    // <div style="padding: 25px;">12313</div>
                    let html = ``
                    ea.request.get({
                        url: ea.url('ajax/composerInfo'),
                    }, function (success) {
                        let data = success.data
                        data.forEach(function (item) {
                            html += `${item.name}  ${item.version}\r\n`
                        })
                        html = `<pre class="layui-code code-demo">${html}</pre>`
                        layer.open({
                            type: 1,
                            title: 'composer 信息',
                            area: ['50%', '90%'],
                            shade: 0.8,
                            shadeClose: true,
                            scrollbar: false,
                            content: html,
                            success: function () {
                                layui.code({ elem: '.code-demo', theme: 'dark', lang: 'php' });
                            }
                        })
                    }, function (error) {
                        console.error(error)
                        return false;
                    })

                }
            })
        },
        editAdmin: function () {
            let form = layui.form
            form.on('radio(loginType-filter)', function (data) {
                let elem = data.elem
                let value = elem.value
                if (value === '2') {
                    let width = screen.width < 768 ? '85%' : '60%'
                    ea.open('绑定谷歌验证码', ea.url('index/set2fa'), width, '75%')
                }
            });
            ea.listen();
        },
        editPassword: function () {
            ea.listen();
        },
        set2fa: function () {
            ea.listen();
        },
    };
});
